package websem.handlers;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashMap;

import websem.model.InfosTerm;
import websem.model.Paragraph;
import websem.model.Term;

public class TermHandler {
	
	private static final int TITLE_WEIGHT = 5;
	private static final int SUBTITLE_WEIGHT = 10;
	private static final int AUTHOR_WEIGHT = 5;
	
	private HashMap<String, Term> terms_list;

	public TermHandler(HashMap<String, Term> terms_list) {
		this.terms_list = terms_list;
	}

	/**
	 * Calculate weight of a term
	 * @param term
	 * @param paragraphNumber
	 * @return
	 */
	protected void calculateWeightAndFrequency(Term term, double paragraphNumber, double averageParagraphCount) {
		// Calculate IDF for the given term
		// IDF = log(Total number of paragraphs / Number of containing paragraphs)
		double containingParagraphs = term.getInfos().size();
		double idf = Math.log(paragraphNumber/containingParagraphs);
		
		for (Paragraph p : term.getInfos().keySet()){
			if (p.getType().equals(Paragraph.TYPE_PARAGRAPH)) {
				InfosTerm infos = term.getInfos().get(p);
				int titleWeight = this.getTitleWeight(infos.getPositions());
				
				// Calculate frequency with IDF*TF
				double freq = new Integer(infos.getPositions().size()).doubleValue();
				double tf = freq / (freq + 0.5 + 1.5 * (p.getCount() / averageParagraphCount));
	
				infos.setWeight(tf*idf * 100 * titleWeight);
				
				term.getInfos().put(p, infos);
			}
		}
	}

	protected int getTitleWeight(ArrayList<Integer> positions) {
		int titleWeight = 0;
		for (Integer value : positions){
			if (value < 0){
				switch (value){
					case -1 : 
						titleWeight += TermHandler.TITLE_WEIGHT;
						break;
					case -2 : 
						titleWeight += TermHandler.SUBTITLE_WEIGHT;
						break;
					case -3 : 
						titleWeight += TermHandler.AUTHOR_WEIGHT;
						break;
					default : break;

				}
			}
		}
		return titleWeight;
	}

	public void fillWeights(double paragraphNumber, double averageParagraphCount) {
		for (String s : this.terms_list.keySet()){
			Term t = this.terms_list.get(s);
			this.calculateWeightAndFrequency(t, paragraphNumber, averageParagraphCount);
		}
	}

	/**
	 * Check if a term is in stoplist
	 * @param string
	 * @return
	 */
	public static boolean isInStopList(String string) {
		boolean isInStopList = false;	
		try{
			FileReader fr = new FileReader("res/Collection/stoplist.txt");
			BufferedReader br = new BufferedReader(fr);
			String ligne;
			while ((br != null) && ((ligne=br.readLine()) != null)){
				if (string.equalsIgnoreCase(ligne.trim())){
					isInStopList = true;
					break;
				}
			}
			fr.close();
			br.close();
		}
		catch (Exception e){
			System.out.println(e.toString());
		}
		
		return isInStopList;
	}
}
